<template>
  <div class="upload">
    <el-select
      v-model="sid"
      placeholder="请选择"
      style="width: 100%; margin-bottom: 30px"
    >
      <el-option
        v-for="item in subjects"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      >
      </el-option>
    </el-select>
    <!-- 文件上传 -->
    <el-upload
      class="upload-demo"
      action=""
      drag
      :auto-upload="false"
      multiple
      :http-request="myupload"
      :on-change="filechange"
      :on-remove="fileremove"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    </el-upload>
    <!-- 提交上传 -->
    <el-button type="primary" style="margin-top: 30px" @click="submitUpload">提交上传</el-button>
  </div>
</template>

<script>
import { uploadfile, allsubjects } from "../api/myReq";
export default {
  name: "upLoad",
  data() {
    return {
      filelist: [],
      subjects: [],
      //   目标科目
      sid: "",
    }
  },
  methods:{
    myupload() {
      //自定义上传行为
      alert("111");
    },
    //添加文件时，同步文件列表
    filechange(file, filelist) {
      // console.log(file);
      console.log(filelist);
      this.filelist = filelist;
    },
    //删除文件时，同步文件列表
    fileremove(file, filelist) {
      //console.log(file);
      console.log(filelist);
      this.filelist = filelist;
    },
    //提交上交
    submitUpload() {
    //   var that = this;
      //校验参数
      console.log(this.sid);
      console.log(this.filelist);
      if ((this.sid == "") || (this.filelist.length == 0)) {
        this.$message.error("请选择文件并选择所属科目后上传");
        return;
      }
      //封装一个formData
      let params = new FormData();
      params.append("sid", this.sid);
      params.append("uid", this.$store.state.user.id);
      // let callbackmsg = "";
      //设置文件对象参数
      this.filelist.forEach((file) => {
        //逐个追加
        params.append("file", file.raw);
      });

      uploadfile(params).then((resp) => {
        if (resp.data.code == 200) {
          this.$message({
            message: resp.data.message,
            duration:1000,
            type: "success",
            // onClose(obj){
            //     //console.log("111");
            //     //回到个人中心->我的上传
            //     that.$router.replace("/home/usercenter?activeName=second");
            // }
          });
        }
      });
    },
  },
  created() {
    allsubjects().then((resp) => {
        console.log(resp);
      this.subjects = resp.data.data;
    });
  },
  mounted() {
    const div = document.querySelector(".el-upload-dragger");
    div.parentElement.style.width = "100%";
    div.style.width = "100%";
  },
};

</script>

<style>
.el-upload-dragger {
  width: 100%;
}
</style>